package com.itheima.app.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.api.R;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.autoconfig.huanxin.HuanXinTemplate;
import com.itheima.domain.db.Question;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.*;
import com.itheima.service.db.QuestionService;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.*;
import com.itheima.utils.ConstantUtil;
import com.itheima.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.Duration;
import java.util.*;

/**
 * @author Guanxing
 * @date 2021/9/25
 */
@Component
public class MakeFriendManager {

    @Reference
    private RecommendUserService recommendUserService;

    @Reference
    private UserInfoService userInfoService;

    @Reference
    private QuestionService questionService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Reference
    private VisitorService visitorService;

    @Reference
    private UserLocationService userLocationService;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @Reference
    private FriendService friendService;

    @Autowired
    private FastFileStorageClient Client;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Reference
    private MakeFriendService makeFriendService;

    //今日佳人
    public RecommendUserVo todayBest() {
        //获取当前用户的id
        Long loginUserId = UserHolder.getId();
        //根据登录用户id查询推荐用户id
        RecommendUser recommendUser = recommendUserService.findBestUser(loginUserId);

        //转换成vo对象
        RecommendUserVo recommendUserVo = new RecommendUserVo();
        //查询用户信息
        UserInfo userInfo = userInfoService.findById(recommendUser.getUserId());

        recommendUserVo.setUserInfo(userInfo);
        recommendUserVo.setFateValue(recommendUser.getScore().longValue());

        return recommendUserVo;
    }

    //推荐列表
    public PageBeanVo findRecommendUserList(Integer page, Integer pageSize) {
        //获得当前登录用户id
        Long loginUserId = UserHolder.getId();
        //根据登录人查询到推荐用户列表
        PageBeanVo pageBeanVo = recommendUserService.findRecommendUserList(page, pageSize, loginUserId);

        List<RecommendUser> items = (List<RecommendUser>) pageBeanVo.getItems();
        List<RecommendUserVo> recommendUserVoList = new ArrayList<>();

        //数据搬家
        for (RecommendUser recommendUser : items) {
            //创建vo对象
            RecommendUserVo recommendUserVo = new RecommendUserVo();
            //查询用户信息
            UserInfo userInfo = userInfoService.findById(recommendUser.getUserId());
            //封装信息
            recommendUserVo.setUserInfo(userInfo);
            recommendUserVo.setFateValue(recommendUser.getScore().longValue());

            recommendUserVoList.add(recommendUserVo);
        }

        pageBeanVo.setItems(recommendUserVoList);

        return pageBeanVo;
    }

    //查询推荐用户详细信息
    public RecommendUserVo findRecommendUserById(Long recommendUserId) {
        //获得登录用户id
        Long loginUserId = UserHolder.getId();
        //查询推荐用户个人信息
        UserInfo userInfo = userInfoService.findById(recommendUserId);

        //查询缘分值
        RecommendUser recommendUser = recommendUserService.findFateValue(loginUserId, recommendUserId);

        //创建vo对象
        RecommendUserVo recommendUserVo = new RecommendUserVo();
        //封装数据
        recommendUserVo.setUserInfo(userInfo);
        recommendUserVo.setFateValue(recommendUser.getScore().longValue());

        return recommendUserVo;
    }

    //查询陌生人问题
    public String findQuestionByUserId(Long userId) {
        //根据id查询问题对象
        Question question = questionService.findByUid(userId);
        if (question == null) {//如果为空给默认数据
            return "你喜欢高山还是流水?";
        }

        //返回数据
        return question.getStrangerQuestion();
    }


    //查询最近访客
    public List<VisitorVo> findVisitors() {
        //获取当前用户id
        Long loginUserId = UserHolder.getId();
        //查看redis中是否有上传登录时间
        String lastTime = stringRedisTemplate.opsForValue().get(ConstantUtil.LAST_ACCESS_TIME + loginUserId);
        //如果没有,直接返回空数据
        if (StringUtils.isEmpty(lastTime)) {
            //存入当前时间
            stringRedisTemplate.opsForValue().set(ConstantUtil.LAST_ACCESS_TIME + loginUserId, System.currentTimeMillis() + "");
            return null;
        }

        //如果有,查询访客记录
        List<Visitor> visitorList = visitorService.findVisitorList(loginUserId, lastTime);
        //创建vo对象
        List<VisitorVo> visitorVoList = new ArrayList<>();
        //数据搬家
        if (CollectionUtil.isNotEmpty(visitorList)) {
            for (Visitor visitor : visitorList) {
                VisitorVo visitorVo = new VisitorVo();
                //查询用户个人信息
                UserInfo userInfo = userInfoService.findById(visitor.getVisitorUserId());
                //查看缘分值
                RecommendUser recommendUser = recommendUserService.findFateValue(loginUserId, visitor.getVisitorUserId());
                visitorVo.setUserInfo(userInfo);
                visitorVo.setFateValue(recommendUser.getScore().longValue());

                visitorVoList.add(visitorVo);
            }
        }

        return visitorVoList;
    }

    //上传位置
    public void saveOrUpdateUserLocation(Double latitude, Double longitude, String addrStr) {
        //保存或者更新位置信息
        userLocationService.saveOrUpdateUserLocation(latitude, longitude, addrStr, UserHolder.getId());
    }

    //附近的人
    public List<NearUserVo> findNearUserList(String gender, Long distance) {
        //获取用户id
        Long userId = UserHolder.getId();

        //调用service查询附近的人
        List<Long> userIdList = userLocationService.findNearUserIdList(userId, distance);

        //处理返回结果
        List<NearUserVo> nearUserVoList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(userIdList)) {
            for (Long uid : userIdList) {
                //根据id查询用户信息
                UserInfo userInfo = userInfoService.findById(userId);

                //排除自己
                if (userId == uid) {
                    continue;
                }

                //排除同性
                if (StringUtils.equals(gender, userInfo.getGender())) {
                    continue;
                }

                //封装vo
                NearUserVo nearUserVo = new NearUserVo();
                nearUserVo.setUserId(uid);
                nearUserVo.setAvatar(userInfo.getAvatar());
                nearUserVo.setNickname(userInfo.getNickname());

                nearUserVoList.add(nearUserVo);
            }
        }

        return nearUserVoList;
    }

    //打招呼
    public void replyStrangerQuestion(String questionUserId, String reply) {
        //获得当前用户id
        Long loginUserId = UserHolder.getId();
        //查询当前用户信息
        UserInfo userInfo = userInfoService.findById(loginUserId);
        //查询问题
        Question question = questionService.findByUid(Long.valueOf(questionUserId));

        //构建map
        Map<String, String> map = new HashMap<>();
        map.put("userId", loginUserId + "");
        map.put("nickname", userInfo.getNickname());
        if (question == null) {
            map.put("strangerQuestion", "远在天边,近在眼前");
        } else {
            map.put("strangerQuestion", question.getStrangerQuestion());
        }
        map.put("reply", reply);
        //发送消息
        String json = JSON.toJSONString(map);
        huanXinTemplate.sendMsg(questionUserId, json);
    }


    //添加联系人
    public void addContacts(String friendId) {
        //当前用户id
        Long loginUserId = UserHolder.getId();
        //添加mongo好友
        friendService.addContacts(loginUserId,Long.valueOf(friendId));
        //添加环信好友
        huanXinTemplate.addContacts(loginUserId,Long.valueOf(friendId));
    }

    //查询联系人列表
    public PageBeanVo findContactList(Integer page, Integer pageSize) {
        //分页查询数据
        PageBeanVo pageBeanVo = friendService.findContactList(page, pageSize ,UserHolder.getId());
        //获得id是集合
        List<Friend> items = (List<Friend>) pageBeanVo.getItems();
        List<ContactVo> voList = new ArrayList<>();
        //数据搬家
        if(CollectionUtil.isNotEmpty(items)){
            //3.转换数据
            for (Friend friend : items) {
                //查询出好友的相关信息
                UserInfo userInfo = userInfoService.findById(friend.getFriendId());
                //封装vo对象
                ContactVo vo = new ContactVo();
                vo.setUserInfo(userInfo);
                vo.setUserId( friend.getFriendId()+"" ); //好友的id
                voList.add(vo);
            }
        }

        pageBeanVo.setItems(voList);
        return pageBeanVo;
    }

    //桃花传音 发送语音
    public Map sendAudio(MultipartFile soundFile) throws IOException {
        StorePath storePath = Client.uploadFile(soundFile.getInputStream(),
                soundFile.getSize(), FileUtil.extName(soundFile.getOriginalFilename()), null);
        String webServerUrl = fdfsWebServer.getWebServerUrl();

        String fullPath = storePath.getFullPath();
        Audio audio = new Audio();
        audio.setUesrId(UserHolder.getId());

        audio.setSoundUrl(webServerUrl + fullPath);
        makeFriendService.sendAudio(audio);
        return null;
    }

    //桃花传音 查询语音
    public UserAudioVo findAudio() {
        //获取当前用户id
        Long loginUserId = UserHolder.getId();
        UserAudioVo userAudioVo = new UserAudioVo();
        Audio audio = null;

        List<Audio> audioList = makeFriendService.findAudio();

        List<Audio> audioList1 = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(audioList)) {
            for (Audio audio1 : audioList) {
                if (audio1.getUesrId() != loginUserId) {
                    audioList1.add(audio1);
                }
            }
            Integer i = RandomUtil.randomInt(0, audioList1.size());
            audio = audioList1.get(i);

            UserInfo userInfo = userInfoService.findById(audio.getUesrId());
            BeanUtil.copyProperties(userInfo, userAudioVo);
            userAudioVo.setAudioAddress(audio.getSoundUrl());




            //判断Redis中还有多少次机会
            String key = ConstantUtil.AUDIO_REMAINIMGTIMES + loginUserId;
            Boolean flag = stringRedisTemplate.hasKey(key);

            //获取当前时间
            Date date = new Date(System.currentTimeMillis());
            //获取当天的最后时间
            Date date1 = DateUtil.endOfDay(date);
            Long time = date1.getTime() - date.getTime();
            if (!flag) {
                stringRedisTemplate.opsForValue().set(key, "10", Duration.ofMillis(time));
            } else {
                String count = stringRedisTemplate.opsForValue().get(key);
                Integer countTimes = Integer.valueOf(count);
                if (countTimes != 0) {
                    countTimes--;
                    stringRedisTemplate.opsForValue().set(key, countTimes.toString(), Duration.ofMillis(time));

                }

            }

            String remainingTimes = stringRedisTemplate.opsForValue().get(key);
            userAudioVo.setRemainingTimes(Integer.valueOf(remainingTimes));
        }
        return userAudioVo;
    }

}
